import { config } from '../../config.js'
import {
  OrderModel
} from '../../models/hdd/orderData.js'
import {
  AuthModel
} from '../../models/hdd/authData.js'
import {
  PersonModel
} from '../../models/hdd/personal.js'
let authModel = new AuthModel()
let orderModel = new OrderModel()
let personModel = new PersonModel()
const {
  $Message
} = require('../../components/base/index')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderInfo: '',
    priSeries: [],
    priSeriesIndex: 0,
    priSeriesText: '',
    secSeries: [],
    secSeriesIndex: 0,
    secSeriesText: '',
    yearsType: '',
    serTypes: [{
        value: '1',
        name: '技术支持'
      },
      {
        value: '2',
        name: '上门服务'
      },
      {
        value: '3',
        name: '到店服务'
      }
    ],
    serTypesIdx: 0,
    maintainType: [{
        value: '1',
        name: '机电'
      },
      {
        value: '2',
        name: '钣金'
      },
      {
        value: '3',
        name: '喷漆'
      }
    ],
    maintainTypeIdx: 0,
    fixTime: '',
    fixAddress: '',
    phone: '',
    price: '',
    failure: '',
    attachments: [],
    attachmentStr: [],
    starIndex: 0,
    ifEdit: false,
    isDoorService: false,
    latitude: '',
    longitude: '',
    FOrderStatus: '',
    FId: '',
  },

  priSeriesSelector: function(e) {
    this.setData({
      priSeriesIndex: e.detail.value,
      priSeriesText: this.data.priSeries[e.detail.value].FName,
      secSeriesIndex: 0
    })
    authModel.getBrandsData({
      pageIndex: 1,
      pageSize: 100,
      refresh: 'true',
      keyword: this.data.priSeriesText,
      unitId: 'fcdb7ae7-fc56-456b-8e20-d621eb7af843',
      listId: '0648e08b-e6aa-4f71-a5b5-8b992cf81636',
      pageCode: 'ATC.Brand.List'
    }).then(res => {
      this.setData({
        secSeries: res.data.data.data.records
      })
      this.setData({
        secSeriesText: this.data.secSeries[this.data.secSeriesIndex].FName
      })
    })
  },

  secSeriesSelector: function(e) {
    console.log(e)
    this.setData({
      secSeriesIndex: e.detail.value,
      secSeriesText: this.data.secSeries[e.detail.value].FName
    })
  },

  yearsTypeInput(e) {
    this.setData({
      yearsType: e.detail.value
    })
  },

  maintainTypeSelector(e) {
    this.setData({
      maintainTypeIdx: e.detail.value
    })
  },

  serTypesSelector(e) {
    if (e.detail.value === '0') {
      this.setData({
        isDoorService: false
      })
    } else {
      this.setData({
        isDoorService: true
      })
    }
    this.setData({
      serTypesIdx: e.detail.value
    })
  },

  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  priceInput(e) {
    this.setData({
      price: e.detail.value
    })
  },

  failureInput(e) {
    this.setData({
      failure: e.detail.value
    })
  },

  fixTimeSelector(e) {
    this.setData({
      fixTime: e.detail.value
    })
  },

  fixAddressInput(e) {
    this.setData({
      fixAddress: e.detail.value
    })
  },

  pickAttachments(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempArr = that.data.attachments
        tempArr.push(res.tempFilePaths[0])
        that.setData({
          attachments: tempArr
        })
      }
    })
  },

  deleteAttachments(e) {
    var tempArr = this.data.attachments
    tempArr.splice(e.currentTarget.id, 1)
    this.setData({
      attachments: tempArr
    })
  },

  selectAddress() {
    let that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.chooseLocation({
                success: function (res) {
                  console.log(res)
                  that.setData({
                    FAdress: res.name
                  })
                },
              })
            },
            fail() {
              wx.showModal({
                showCancel: false,
                title: '提示',
                content: '请打开位置开关',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(res) {
                        if (res.authSetting['scope.userLocation']) {
                          wx.chooseLocation({
                            success: function (res) {
                              that.setData({
                                fixAddress: res.name,
                                latitude: res.latitude,
                                longitude: res.longitude,
                              })
                            },
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        } else {
          wx.chooseLocation({
            success: function (res) {
              that.setData({
                fixAddress: res.name,
                latitude: res.latitude,
                longitude: res.longitude,
              })
            },
          })
        }
      }
    })
  },

  checkData() {
    if (this.data.yearsType.length === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请输入年款',
      })
      return
    }
    if (this.data.isDoorService && this.data.fixAddress.length === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请输入维修地点',
      })
      return
    }
    if (this.data.phone.length === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请输入联系电话',
      })
      return
    }
    if (this.data.price.length === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请输入预估维修价',
      })
      return
    }
    if (this.data.attachments.length === 0) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请选择至少一张图片',
      })
      return
    }

    if (this.data.price > 1000000) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '预估维修价金额不能超过1000000',
      })
      return
    }
    this.uploadAttachment(this.data.attachments)
  },

  uploadAttachment(data) {
    var that = this
    var i = data.i ? data.i : 0
    if (data.length === i) {
      var tempStrs
      for (var i = 0; i < this.data.attachmentStr.length; i++) {
        if (i == 0) {
          tempStrs = this.data.attachmentStr[i]
        } else {
          tempStrs = tempStrs + '|' + this.data.attachmentStr[i]
        }
      }
      that.releaseOrder(tempStrs)
      return
    }
    wx.uploadFile({
      url: `${config.api_base_url}api/Ecp.Picture.upload.jup`,
      filePath: data[i],
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        'Cookie': 'MEETREND_CRM_TOKEN=' + wx.getStorageSync('token')
      },
      formData: {
        'user': 'test'
      },
      success: function (res) {
        var tempArr = that.data.attachmentStr
        tempArr.push(JSON.parse(res.data).data.pictureId)
        that.setData({
          attachmentStr: tempArr
        })
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        })
      },
      complete: function () {
        i++
        data.i = i
        that.uploadAttachment(data)
      }
    })
  },

  releaseOrder(pictureIds) {
    let param
    if (this.data.isDoorService) {
      param = {
        FYear: this.data.yearsType,
        FCarInformation: this.data.priSeriesText + this.data.secSeriesText + this.data.yearsType,
        FEstimateSum: this.data.price,
        FRemark: this.data.failure,
        FMobile: this.data.phone,
        FMaintainTime: this.data.fixTime,
        FMaintainSite: this.data.fixAddress,
        FMaintainType: this.data.maintainType[this.data.maintainTypeIdx].value,
        FWaitType: this.data.serTypes[this.data.serTypesIdx].value,
        FBrand: this.data.secSeries[this.data.secSeriesIndex].FId,
        FSeries: this.data.priSeries[this.data.priSeriesIndex].FId,
        FAttachment: pictureIds
      }
    } else {
      param = {
        FYear: this.data.yearsType,
        FCarInformation: this.data.priSeriesText + this.data.secSeriesText + this.data.yearsType,
        FEstimateSum: this.data.price,
        FRemark: this.data.failure,
        FMobile: this.data.phone,
        FMaintainType: this.data.maintainType[this.data.maintainTypeIdx].value,
        FWaitType: this.data.serTypes[this.data.serTypesIdx].value,
        FBrand: this.data.secSeries[this.data.secSeriesIndex].FId,
        FSeries: this.data.priSeries[this.data.priSeriesIndex].FId,
        FAttachment: pictureIds
      }
    }
    orderModel.saveOrder({
      args: {
        data: [param]
      }
    }).then(res => {
      console.log(res)
      return orderModel.submitOrder({
        args: {
          method: 'Submit',
          pageCode: 'ATC.Order.Edit',
          entityIds: res.data.data.entityIds,
        }
      })
    }).then(res => {
      if (res.data.success) {
        $Message({
          content: '提交成功',
          type: 'success',
          duration: 2
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '发布订单'
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#FF7136',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })

    if (options.FId) {
      this.setData({
        ifEdit: false,
        FId: options.FId
      })
      orderModel.getOrderDetail({
        entityId: options.FId
      }).then(res => {
        console.log(res)
        let dic = res.data.data.editJson.data
        if (dic.FWaitType === '1') {
          this.setData({
            isDoorService: false
          })
        } else {
          this.setData({
            isDoorService: true
          })
        }
        this.setData({
          priSeriesText: dic.FSeries$,
          secSeriesText: dic.FBrand$,
          yearsType: dic.FYear,
          maintainTypeIdx: parseInt(dic.FMaintainType) - 1,
          serTypesIdx: parseInt(dic.FWaitType) - 1,
          fixTime: dic.FMaintainTime,
          fixAddress: dic.FMaintainSite,
          phone: dic.FMobile,
          price: dic.FEstimateSum,
          failure: dic.FRemark,
          attachments: dic.FAttachment.split('|'),
          FOrderStatus: dic.FOrderStatus,
        })
      })
    } else {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      this.setData({
        fixTime: year + '-' + month + '-' + day,
      })
      authModel.getSeriesData({
        pageIndex: 1,
        refresh: 'true',
        unitId: '5570d564-d242-4495-a1ea-ad97459a8983',
        listId: '4e3a0ed8-c4ec-41db-92ac-f45670f6edff',
        pageCode: 'ATC.Series.List'
      }).then(res => {
        this.setData({
          priSeries: res.data.data.data.records
        })
        this.setData({
          priSeriesText: this.data.priSeries[this.data.priSeriesIndex].FName
        })
        authModel.getBrandsData({
          pageIndex: 1,
          pageSize: 100,
          refresh: 'true',
          keyword: this.data.priSeriesText,
          unitId: 'fcdb7ae7-fc56-456b-8e20-d621eb7af843',
          listId: '0648e08b-e6aa-4f71-a5b5-8b992cf81636',
          pageCode: 'ATC.Brand.List'
        }).then(res => {
          console.log(res)
          this.setData({
            secSeries: res.data.data.data.records
          })
          this.setData({
            secSeriesText: this.data.secSeries[this.data.secSeriesIndex].FName
          })
        })
      })
      personModel.getMerchantInfo()
        .then(res => {
          this.setData({
            phone: res.data.data.data.FMobile
          })
        })
      this.setData({
        ifEdit: true
      })
    }
  },

  fixDesInput(e) {
    this.setData({
      FFixDes: e.detail.value
    })
  },

  cencelOrder() {
    this.setData({
      visible: false
    })
    wx.navigateTo({
      url: `/pages/cancelOrder/cancelOrder?FId=${this.data.orderDetail.FId}&phone=${this.data.orderDetail.FMobile}`
    })
  },

  openModal() {
    this.setData({
      visible: true
    })
  },

  closeModal() {
    this.setData({
      visible: false
    })
  },

  completeOrder() {
    wx.navigateTo({
      url: `/pages/orderEvaluating/orderEvaluating?FId=${this.data.FId}&price=${this.data.price}`
    })
  },

  attachmentClick(e) {
    if(this.data.ifEdit) {
      return
    }
    var urls = []
    var currentUrl
    for (var i = 0; i < this.data.attachments.length; i++) {
      var url = 'https://www.myhr100.com:4200/Ecp.Picture.view.img?pictureId=' + this.data.attachments[i]
      urls.push(url)
    }
    currentUrl = 'https://www.myhr100.com:4200/hdd/Ecp.Picture.view.img?pictureId=' + this.data.attachments[e.currentTarget.id]
    wx.previewImage({
      current: currentUrl,
      urls: urls,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})